package com.disapand.strongarmy.configuration

import cn.dev33.satoken.context.model.*
import cn.dev33.satoken.interceptor.*
import cn.dev33.satoken.router.*
import cn.dev33.satoken.stp.*
import cn.dev33.satoken.thymeleaf.dialect.*
import com.disapand.strongarmy.service.*
import org.springframework.context.annotation.*
import org.springframework.web.servlet.config.annotation.*


/**
 *
 * @auth disapand
 * @date 2021/10/17 - 21:46 - 星期日
 *
 */
@Configuration
class SaTokenConfigure(private val accountService: AccountService) : WebMvcConfigurer {

    /**
     * 注册 thymeleaf 标签方言
     *
     * @return
     */
    @Bean
    fun getSaTokenDialect(): SaTokenDialect {
        return SaTokenDialect()
    }

    /**
     * 路由拦截器权限过滤
     *
     * @param registry
     */
    override fun addInterceptors(registry: InterceptorRegistry) {
        registry.addInterceptor(SaRouteInterceptor { _: SaRequest, _: SaResponse, _: Any ->
            // 判断当前登录账号是否具有 super-admin 权限，是的话跳过所有鉴权操作
            SaRouter.match {
                val loginId = StpUtil.getLoginIdAsInt()
                val roles = accountService.getRoles(loginId)
                roles.any { it.role == "super-admin" }
            }.stop()
        })
            .addPathPatterns("/**")
            .excludePathPatterns("/accounts/login", "/", "/error", "/favicon.ico", "/images/**")
    }
}